package dao;

import text.UserBean;
import utils.JDBCUtil;

import java.sql.*;

public class LoginDao {
    public static boolean login(UserBean user){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        //如果用户名和密码都不为空，执行
        if (user.getUsername() != null && user.getPassword() != null){
            try {
                //注册驱动和连接数据库
                conn = JDBCUtil.getConnection();
                //提交事务
                conn.setAutoCommit(false);
                //输入sql语句
                String sql = "select * from user where username = ? and password = ?";
                //提交sql语句
                ps = conn.prepareStatement(sql);
                // 设置参数
                ps.setString(1, user.getUsername());
                ps.setString(2, user.getPassword());
                //执行sql语句
                rs = ps.executeQuery();
                //提交事务
                conn.commit();
                return rs.next();
            } catch (Exception e) {
                //在conn不为空的情况下回滚事务
                if (conn != null) {
                    try {
                        conn.rollback();
                    } catch (SQLException ex) {
                        ex.printStackTrace();
                    }
                }
                e.printStackTrace();
            } finally {
                JDBCUtil.close(rs, ps, conn);
            }
        }
        //任意一个为空，直接返回false
        return false;
    }
}

